<template>
  <el-upload
    ref='uploadRef'
    :action="exportUrl[props.url]"
    :multiple="multiple"
    :headers="{
      Authorization: userStore.token
    }"
    :accept="accept"
    :show-file-list="false"
    :limit="limit"
    :on-progress="onProgress"
    :on-success="importFileSuccess"
    :key="keyValue"
    :on-exceed="handleExceed"
  >
    <slot :loading="loading" :disabled="disabled" />
  </el-upload>
</template>
<!-- 不带下载任务 -->
<script setup>
import { useUserStore } from '@/pinia/modules/user'
import { ElMessage,genFileId  } from 'element-plus'
const exportUrl = {
  trainOrgImport: '/api/biz/trainingOrganization/import', // 培训机构导入
  trainRecordImport: '/api/biz/trainingRecords/import' // 培训记录导入
}

const userStore = useUserStore()
const props = defineProps({
  url: {
    type: String,
    default() {
      return ''
    }
  },
  disabled: {
    type: Boolean,
    default: false
  },
  multiple: {
    type: Boolean,
    default: false
  },
  accept: {
    type: String,
    default() {
      return '.xlsx,.xls'
    }
  },
  limit: {
    type: Number,
    default: 1
  }
})

const loading = ref(false)
const keyValue = ref(new Date().getTime())

const emit = defineEmits(['success'])
const uploadRef = ref(null)

const handleExceed = (files) => {
    console.log(uploadRef)
    uploadRef.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    uploadRef.value.handleStart(file)
    uploadRef.value.submit()
}
const importFileSuccess = res => {
  console.log(res)
  if (res.succeed) {
    ElMessage.success('导入成功')
    emit("success")
    loading.value = false
  } else {
    ElMessage.error({
      dangerouslyUseHTMLString: true,
      message: res.msg
    })
    loading.value = false
    keyValue.value = new Date().getTime()
  }
}

const onProgress = e => {
  // console.log(e)
  loading.value = true
}
</script>

<style scoped lang="scss"></style>
